﻿using IdentityServer4.Models;
using IdentityServer4.Validation;
using SJ.Platform.EFCore.DBOperation.DBOperation.MySQL.Sys;
using SJ.Platform.EFCore.Model;
using SJ.Platform.EFCore.Model.UserManager;
using System.Security.Claims;

namespace SJ.Platform.IdentityServer
{
    public class CustomResourceOwnerPasswordValidator : IResourceOwnerPasswordValidator
    {
        private readonly Sys_LoginHandle sys_LoginHandle;
        public CustomResourceOwnerPasswordValidator(SJDBContext dbContext)
        {
            sys_LoginHandle = new Sys_LoginHandle(dbContext);
        }
        /// <summary>
        /// 用户验证
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public async Task ValidateAsync(ResourceOwnerPasswordValidationContext context)
        {
            // 在这里实现你的验证逻辑
            var loginUser = sys_LoginHandle.Login(context.UserName, context.Password).Result;
            if (loginUser != null)
            {
                SysLogin sys_User = loginUser;

                // 验证通过，设置验证结果
                context.Result = new GrantValidationResult(sys_User.Id.ToString(), "Validate");
            }
            else
            {
                // 验证失败，设置错误信息
                context.Result = new GrantValidationResult(TokenRequestErrors.InvalidGrant, "用户名或密码错误");
            }
        }
    }
}
